import os
import mimetypes
from binaryornot.check import is_binary

def write_to_file(value):
    with open('../hmac.txt', 'a') as the_file:
        the_file.write(value)
        the_file.write('\n')
        the_file.close()

def parse_file(filepath):
    with open(filepath) as fp:
        line = fp.readline()
        cnt = 1
        while line:
            if line.find('hmac') != -1 or line.find('HMAC') != -1:
                #print line
                #print("Line {}: {}".format(cnt, line.strip()))
                print filepath
                print cnt
                write_to_file('=============================================================')
                write_to_file(str(filepath))
                write_to_file(str(cnt))
                write_to_file(str(line.strip()))
                write_to_file('=============================================================')
            line = fp.readline()
            cnt += 1

def search_files(directory='.', extension=''):
    extension = extension.lower()
    for dirpath, dirnames, files in os.walk(directory):
        for name in files:
            if extension and name.lower().endswith(extension):
                filename = os.path.join(dirpath, name)
                if not is_binary(filename):
                    #print filename
                    parse_file(filename)
            elif not extension:
                filename = os.path.join(dirpath, name)
                if not is_binary(filename):
                    #print filename
                    parse_file(filename)
search_files()
